package com.sigmatrix.h5.web.rebate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.sigmatrix.h5.entity.DisRebateScanCodeError;
import com.sigmatrix.h5.enums.CrmAcctType;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.service.DisRebateScanCodeErrorService;
import com.sigmatrix.h5.service.HierarchyRebateService;
import com.sigmatrix.h5.service.WeChatSmallProgramService;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.utils.Constants;
import com.sigmatrix.h5.utils.JsonUtils;
import com.sigmatrix.h5.utils.SessionUtils;
import com.sigmatrix.h5.web.BaseController;
import com.sigmatrix.h5.web.Result;
import com.sigmatrix.h5.web.args.HierarchyRebate;
import com.sigmatrix.h5.web.args.HierarchyScan;
import com.sigmatrix.h5.web.mode.ErrorMessage;
import com.sigmatrix.h5.web.mode.QrCode;
import com.sigmatrix.sc.jdbc.common.lang.Session;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags="层级扫码")
@RequestMapping("/rebate/hierarachy/api/rebate")
@RestController
public class HierarchyRebateController extends BaseController{
	Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private HierarchyRebateService hierarchyRebateService; 
	@Autowired
	private DisRebateScanCodeErrorService disRebateScanCodeErrorService; 
	@Autowired
	private WeChatSmallProgramService weChatSmallProgramService;
	private Kryo kryo = new Kryo();
	/**
	 * 
	 *@Title: scanCodeRebate
	 *@Description: 扫码返利
	 *@return Result
	 *@author MH
	 *@date 2017年12月7日 下午2:01:45
	 *@param vo
	 *@return
	 */
	@ApiOperation("扫码")
	@PostMapping("submit")
	public Result<String> scanCodeRebate(@RequestBody HierarchyScan vo){
		logger.info("扫码提交数据："+JsonUtils.objectToJson(vo));
		if(CommonUtils.isEmpty(vo))return error("参数不能为空");
		hierarchyRebateService.submitTask(vo);
//		HierarchyRebate rebate = new HierarchyRebate();
//		rebate.setDealerId(vo.getDealerId());
//		rebate.setLat(vo.getLat());
//		rebate.setLng(vo.getLng());
//		rebate.setQrCode(vo.getQrCode().get(0));
//		hierarchyRebateService.scanCode(rebate);
		return ok("您已经提交申请，处理完以后会微信通知您");
	}
	
	@RabbitListener(queues="${rabbit.bindings[1].queue}")
	public void dealWithSubmits(Message message){
		logger.info("层级返利收到一条消息："+message);
		//ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(message.getBody()));
		Input input = new Input(message.getBody());
		HierarchyScan scan = kryo.readObject(input, HierarchyScan.class);
		input.close();
		Session.set(scan.getUser());
		List<ErrorMessage> list = new ArrayList<ErrorMessage>();
		QrCode code = null;
		for(String qrCode :scan.getQrCode()){
			String msg = "成功";
			HierarchyRebate rebate = new HierarchyRebate();
			BeanUtils.copyProperties(scan, rebate);
			rebate.setQrCode(qrCode);
			String status = Constants.DATA_SUCCESS;
			try{
				hierarchyRebateService.scanCode(rebate);
			}catch(MessageException e){
				msg = e.getMessage();
				logger.error(msg,e);
				status = Constants.DATA_FAILURE;
				code = (QrCode) e.getData();
				try {
					//添加扫码异常记录
					saveErrorScanCode(msg,rebate,code,qrCode);
				} catch (Exception e1) {
					logger.error(e1.getMessage());
					msg = "记录失败信息异常";
					status = Constants.DATA_FAILURE;
				}
			}catch (Exception e) {
				msg = e.getMessage();
				logger.error(msg,e);
				status = Constants.DATA_FAILURE;
				try {
					//添加扫码异常记录
					saveErrorScanCode(msg,rebate,code,qrCode);
				} catch (Exception e1) {
					logger.error(e1.getMessage(),e1);
					msg = "记录失败信息异常";
					status = Constants.DATA_FAILURE;
				}
			}
			ErrorMessage errorMessage = ErrorMessage.creat(status,qrCode, msg);
			list.add(errorMessage);
		}
		weChatSmallProgramService.submitTask(list, scan.getMessageInfo());;
	}

	private void saveErrorScanCode(String msg, HierarchyRebate rebate, QrCode code,String qrCode) {
		DisRebateScanCodeError error = new DisRebateScanCodeError();
		error.setErrorMessage(msg);
		error.setDealerId(rebate.getDealerId());
		if (CrmAcctType.TERMINAL_SHOP.value.equals(SessionUtils.getAcctType())) {
			error.setScanType(CrmAcctType.TERMINAL_SHOP.value);
			error.setScanId(SessionUtils.getTerminalShopId());
		}else if(CrmAcctType.DEALER.value.equals(SessionUtils.getAcctType())) {
			error.setScanType(CrmAcctType.DEALER.value);
			error.setScanId(SessionUtils.getDealerId());
		}
		error.setScanTime(new Date());
		error.setAccount(SessionUtils.getAccount());
		error.setProductId(CommonUtils.isEmpty(code)? null : code.getProductId());
		error.setCodeType(CommonUtils.isEmpty(code) ? null : code.getPackLevel().shortValue());
		error.setOpenId(CommonUtils.isEmpty(rebate) ? "" : rebate.getOpenId());
		error.setQrCode(qrCode);
		error.setSeqNum(CommonUtils.isEmpty(code) ? "" : code.getSeqNum());
		disRebateScanCodeErrorService.save(error);
	}
}
